using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Serialization;

namespace net.notdot.Attercop
{
    [Serializable()]
    public class PongMessage : Message, UdpMessage
    {
        public readonly int PingId;

        static PongMessage() { ClientInstance.AddMessageHandler<PongMessage>(); }

        public PongMessage(MessageAddressing addressing, int pingId)
            : base(addressing)
        {
            this.PingId = pingId;
        }

        protected PongMessage(MessageReader reader)
            : base(reader)
        {
            reader.BeginRegion();
            reader.ReadByte();  //Version
            PingId = reader.ReadInt32();
            reader.EndRegion();
        }

        public override void Serialize(MessageWriter writer)
        {
            base.Serialize(writer);

            writer.BeginRegion();
            writer.Write((byte)0);  //Version
            writer.Write(PingId);
            writer.EndRegion();
        }

        public virtual void Handle(ClientInstance c)
        {
            lock (c.pings)
            {
                //If we don't know the peer, or didn't send the ping, return
                if (this.PeerState == PeerState.Unknown) return;
                if (!c.pings.ContainsKey(PingId)) return;

                Peer p = c.Peers[this.Addressing.From];

                //This is a ping reply to a ping we sent. Mark the peer as
                //introduced.
                c.pings.Remove(PingId);

                if (!p.m_Introduced)
                {
                    p.m_Introduced = true;
                    c.RaisePeerJoin(p);
                }
            }
        }
    }
}
